<template>
    <div :id="item.id" class="echarts_item"  ref="echarts_item">
        <a-spin :spinning="search_loading">
          <div :id="item.type + item.id"></div> 
        </a-spin>
    </div>
</template>

<script>
import China from '@/assets/China.json';
import ElementResize from './elementResize'
import _ from "lodash";
import { mapActions } from 'vuex';
  export default {
    props: ['item', 'remark', 'dataMapping', 'display','datasetList', 'itemGridHeight', 'search_loading'],
    data() {
      return {
        myChart: null,
        mainWidth: null,
        mainHeight: 300,
        ChinaMap: null,
        chartsLoading: true,
        map: {},
        option: {
          grid:{
            left: '5%',
            right: '5%',
            // top: '3%',
            bottom: '5%',
            containLabel: true
          },
          legend: {},
          dataset: [],
          tooltip: {
            trigger: 'axis'
          },
          toolbox: {},
          xAxis: {
            type: 'category'
          },
          yAxis: {},
          series: []
        },
        funnelConfig: {}
      }
    },
    components: {
      ElementResize
    },
    computed: {

    },
    watch: {
    },
    methods: {
      ...mapActions('custom', ['getUpdateReportDs']),
      getFunnelConfig () {
          return new Promise((resolve, reject)=> {
              this.getUpdateReportDs({ id: this.dataMapping.datasetId })
                  .then(res => {
                      this.funnelConfig = JSON.parse(res.data.config).config;
                      resolve(this.setFunnelOption());
                  })
                  .catch(err =>{
                      reject(err)
                  })

          })
      },
      setFunnelOption () {
        let resultSet = this.datasetList[this.dataMapping.datasetId];
          if (this.datasetList[this.dataMapping.datasetId] && this.datasetList[this.dataMapping.datasetId].length > 0) {
              let seriesData = [];
              let seriesName = "总体";
              let startStepValue = 1;
              let endStepValue = 0;
              let prevStep = null;
              for (let j = 0; j < this.funnelConfig.funnel.steps.length; j++) {
                  let step = this.funnelConfig.funnel.steps[j];
                  if (step.order === 1) {
                      startStepValue = resultSet[0][
                          step.event.toLowerCase() + "_" + step.order
                      ];
                  } else if (step.order === this.funnelConfig.funnel.steps.length) {
                      endStepValue = resultSet[0][
                          step.event.toLowerCase() + "_" + step.order
                      ];
                  }
                  let rate = 0;
                  if (step.order === 1) {
                      rate = 100;
                  } else if (
                      resultSet[0].hasOwnProperty(
                          prevStep.event.toLowerCase() + "_" + prevStep.order
                      )
                  ) {
                      let a =
                          resultSet[0][step.event.toLowerCase() + "_" + step.order] *
                          100;
                    let b = resultSet[0][
                        prevStep.event.toLowerCase() + "_" + prevStep.order
                    ];

                    if (b == 0) {
                        rate = 0;
                    } else {
                        rate = Math.ceil(a / b);
                    }
                  }
                  seriesData.push({
                    value: resultSet[0][
                      step.event.toLowerCase() + "_" + step.order
                      ],
                      name: step.name,
                      rate: rate
                  });
                  prevStep = step;
              }
              return seriesData
          } else {
            return []
          }
      },
      getUnit (measureName) {
        let unit = "";
          switch (measureName) {
            case "session_id":
              unit = "会话";
              break;
            case "eship_id":
              unit = "人";
              break;
            default:
              unit = "";
              break;
          }
          return unit;
      },
      initCharts () {
        this.$nextTick(() => {
          if (this.myChart) {
            this.myChart.dispose();//销毁
            this.myChart = null;
          }
          this.initData();
          if (this.remark) {
            this.mainHeight = this.$refs.echarts_item.clientHeight - 60
          } else {
            this.mainHeight = this.$refs.echarts_item.clientHeight - 40
          }
          this.mainWidth = this.$refs.echarts_item.clientWidth
          this.myChart = this.$echarts.init(document.getElementById(this.item.type + this.item.id), 'light', {height: this.mainHeight, width: this.mainWidth})
        
          this.option.series.splice(0, this.option.series.length)
          if (this.item.type == 'funnel') {
              this.getFunnelConfig().then(res => {
                this.option.dataset.push({
                    source: res
                })
                this.option.series.push({
                  type: 'funnel',
                  encode: {
                    itemName: "name"
                  },
                  bottom: 12,
                })
                if (this.display.label) {
                    this.option.series[0].label = {...this.display.label,
                        formatter: params =>{
                            return (
                                params.data.name +
                                "\n" +
                                params.data.value +
                                this.getUnit(this.funnelConfig.funnel.measure.name) +
                                "(" +
                                params.data.rate +
                                "%)"
                            );
                        }
                    }
                }
                if (this.display.legend && this.display.legend.show) {
                    this.option.legend = this.display.legend
                } else {
                    delete this.option.legend
                }
                if (this.display.toolbox && this.display.toolbox.show) {
                    for(let key in this.display.toolbox){
                        if(key == 'show'){
                            this.option.toolbox[key] = this.display.toolbox[key]
                        } 
                        let feature = this.display.toolbox[key]
                        if(key == 'feature' && feature.length) {
                            this.option.toolbox.feature = {}
                            for(let i=0; i<feature.length; i++){
                                if(feature[i] == 'saveAsImage') {
                                    this.option.toolbox.feature[feature[i]] = {type: 'png'}
                                }
                                if(feature[i] == 'dataView') {
                                    this.option.toolbox.feature[feature[i]] = {show: true}
                                }
                            }
                        }
                    }
                } else {
                    delete this.option.toolbox
                }
                delete this.option.xAxis
                delete this.option.yAxis
                delete this.option.tooltip
                delete this.option.grid
                this.myChart.setOption(this.option, true);
              })
              return
          }
          this.dataMapping.forEach(data => {
            for (let key in this.map) {
              if (data.datasetId == key) {
                if (this.item.type == 'pie' || this.item.type == 'loop') {
                  this.option.series.push({
                    type: 'pie',
                    name: data.name,
                    datasetIndex: this.map[key],
                    encode: {
                      itemName: data.itemName,
                      value: data.value
                    },
                    radius: this.display.series[0].radius,
                    emphasis: {}
                  })
                } else {
                  if (this.item.type == 'line' || this.item.type == 'area') {
                    if (this.item.type == 'line') {
                      this.option.series.push({
                        type: 'line',
                        name: data.name,
                        datasetIndex: this.map[key],
                        encode: {
                          x: data.x,
                          y: data.y
                        },
                        emphasis: {}
                      })
                    } else {
                      this.option.series.push({
                        type: 'line',
                        name: data.name,
                        areaStyle: {},
                        datasetIndex: this.map[key],
                        encode: {
                          x: data.x,
                          y: data.y
                        },
                        emphasis: {}
                      })
                    }
                  } else if(this.item.type == 'bar' || this.item.type == 'strip') {
                    this.option.series.push({
                      type: 'bar',
                      datasetIndex: this.map[key],
                      name: data.name,
                      encode: {
                        x: this.item.type == 'bar' ? data.x : data.y,
                        y: this.item.type == 'bar' ? data.y : data.x
                      },
                      emphasis: {}
                    })
                  } else {
                    if (this.item.type == 'map') {
                      this.option.series.push({
                        type: 'map',
                        mapType: data.mapType,
                        datasetIndex: this.map[key],
                        zoom: 1.7,
                        nameMap: {
                          '北京市': '北京市',
                          '天津市': '天津市',
                          '河北省': '河北省',
                          '山西省': '山西',
                          '内蒙古自治区': '内蒙古自治区',
                          '辽宁省': '辽宁',
                          '吉林省': '吉林',
                          '黑龙江省': '黑龙江省',
                          '上海市': '上海',
                          '江苏省': '江苏省',
                          '浙江省': '浙江省',
                          '安徽省': '安徽',
                          '福建省': '福建省',
                          '江西省': '江西',
                          '山东省': '山东省',
                          '河南省': '河南',
                          '湖北省': '湖北省',
                          '湖南省': '湖南',
                          '广东省': '广东',
                          '广西壮族自治区': '广西壮族自治区',
                          '海南省': '海南',
                          '重庆市': '重庆',
                          '四川省': '四川省',
                          '贵州省': '贵州',
                          '云南省': '云南',
                          '西藏自治区': '西藏自治区',
                          '陕西省': '陕西',
                          '甘肃省': '甘肃',
                          '青海省': '青海省',
                          '宁夏回族自治区': '宁夏回族自治区',
                          '新疆维吾尔自治区': '新疆'
                        }
                      })
                    } else {
                      if (this.item.type == 'group') {
                        this.option.series.push({
                          type: 'line',
                          name: data.name,
                          datasetIndex: this.map[key],
                          encode: {
                            x: data.x,
                            y: data.y
                          },
                          emphasis: {}
                        })
                        this.option.series.push({
                          type: 'bar',
                          name: data.name,
                          datasetIndex: this.map[key],
                          encode: {
                            x: data.x,
                            y: data.y
                          },
                          emphasis: {}
                        })
                      } else {
                        this.option.series.push({
                          type: this.item.type,
                          name: data.name,
                          datasetIndex: this.map[key],
                          encode: {
                            x: data.x,
                            y: data.y
                          },
                          emphasis: {}
                        })
                      }
                    }
                  }
                }
              }
            }
          })
          if (this.item.type == 'strip') {
            this.option.xAxis.type = 'value'
            this.option.yAxis.type = 'category'
          } else if (this.item.type == 'pie' || this.item.type == 'loop') {
            this.option.tooltip = {
              trigger: 'item',
            }
            delete this.option.xAxis
            delete this.option.yAxis
          }

          // 高亮显示
          // 聚焦效果
          if(this.display.emphasis && this.display.emphasis.focus){
            for (let i = 0; i < this.option.series.length; i++) {
              this.option.series[i].emphasis.focus = this.display.emphasis.focus
            }
          }
          // 放大效果
          if(this.display.emphasis&&this.display.emphasis.scale){
            for (let i = 0; i < this.option.series.length; i++) {
              this.option.series[i].emphasis.scale =  this.display.emphasis.scale
            }
          }
          // 线条样式
          if (this.display.lineStyle) {
            for (let i = 0; i < this.option.series.length; i++) {
              this.option.series[i].lineStyle = this.display.lineStyle
            }
          }
          // 线条平滑处理
          if (this.display.smooth) {
            for (let i = 0; i < this.option.series.length; i++) {
              this.option.series[i].smooth = this.display.smooth
            }
          }
          // 目标线
          if (this.display.markLine && this.display.markLine.show) {
            for (let i = 0; i < this.option.series.length; i++) {
              this.option.series[i].markLine = {data: this.display.markLine.data}
              this.option.series[i].markLine.label = { position: 'middle' }
            }
          }
          // 图形上的文本标签
          if (this.display.label) {
            for (let i = 0; i < this.option.series.length; i++) {
              this.option.series[i].label = this.display.label
            }
          }
          // 鼠标缩放和平移
          if(this.display.roam) {
            this.option.roam = this.display.roam
          }

          // 设置工具箱
          if (this.display.toolbox) {
            this.option.grid.top = '40'
            for(let key in this.display.toolbox){
              if(key == 'show'){
                this.option.toolbox[key] = this.display.toolbox[key]
              } 
              let feature = this.display.toolbox[key]
              if(key == 'feature' && feature.length) {
                this.option.toolbox.feature = {}
                for(let i=0; i<feature.length; i++){
                  if(feature[i] == 'saveAsImage') {
                    this.option.toolbox.feature[feature[i]] = {type: 'png'}
                  }
                  if(feature[i] == 'dataView') {
                    this.option.toolbox.feature[feature[i]] = {show: true}
                  }
                }
              }
            }
          }

          // 设置图例
          if (this.display.legend && this.display.legend.show) {
            this.option.grid.top = "16%"
            this.option.legend = this.display.legend
          } else {
            delete this.option.legend
          }

          if (this.item.type == 'map') {
            this.$echarts.registerMap('China', China)
            delete this.option.xAxis
            delete this.option.yAxis
            delete this.option.legend
            this.option.center = [110, 36]
            this.option.tooltip = {
              trigger: 'item',
            }
            this.option.visualMap = {
              ...this.display.visualMap,
              min: Number(this.display.visualMap.min),
              max: Number(this.display.visualMap.max)
            }
          }
          this.myChart.setOption(this.option);
        })
        // 绘制图表
      },
      initData () {
        this.option.dataset.splice(0,this.option.dataset.length)
        if (this.item.type == 'map') {
          this.dataMapping.forEach((data, index) => {
            let dataMap = [];
            let dataset = this.datasetList[data.datasetId]
            this.map[data.datasetId] = index;
            if (dataset) {
              dataset.forEach(item => {
                dataMap.push({
                  name: item[data.name],
                  value: item[data.value]
                })
              })
              this.option.dataset.push({source: dataMap})
            } else {
              this.option.dataset.push({source: []})
            }
          })
        } else if (this.item.type == 'funnel') {

        } else {
          let mapData = _.cloneDeep(this.dataMapping);
          for (let i = 0; i < mapData.length; i ++) {
            let datasetId = mapData[i].datasetId;
            this.option.dataset.push({source: this.datasetList[datasetId]});
            this.map[datasetId] = i;
          }
        }
      }
    },
    mounted() {
      window.addEventListener('resize', this.initCharts);
      ElementResize.on(document.getElementById(this.item.id), () => {
        this.$nextTick(() => {
          this.initCharts();
        });
      });
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.initCharts);
      if (this.myChart) {
        this.myChart.dispose();//销毁
        this.myChart = null;
      }
    },
  }
</script>

<style scoped>
.echarts_item {
  height: 100%;
  width: 100%;
  /* height: calc(100% - 60px); */
}

.ant-spin-nested-loading {
  height: 100%;
}

.ant-spin-nested-loading>>>.ant-spin-container {
  height: 100%;
}
</style>